package com.example.ext.jwt;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

public class JwtFilter extends GenericFilterBean {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletRequest request = (HttpServletRequest) servletRequest;
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        final String authHeader = request.getHeader(TokenUtils.AUTH_HEADER);
        if(!"1".equals(request.getHeader("x-app"))
                && !request.getServletPath().equals("/api/user/upload")
                && !request.getServletPath().equals("/api/elevator/getEleInfoBy96333Code")
                && !request.getServletPath().equals("/api/user/uploadElevators")
                && !request.getServletPath().equals("/api/user/uploadPlanDetail")
                && !request.getServletPath().equals("/api/user/uploadParty")
                && !request.getServletPath().equals("/api/user/uploadUser")
                && !request.getServletPath().equals("/api/role/queryList")
                && !request.getServletPath().equals("/api/user/uploadbig")
                && !request.getServletPath().startsWith("/api/userElevator")
                && !request.getServletPath().startsWith("/api/uploadPublicUserElevator")
                && !request.getServletPath().equals("/api/appraisal/add")
                && !request.getServletPath().equals("/api/appraisal/good")
                && !request.getServletPath().contains("/api/user/deleteUpload/")
                && !request.getServletPath().equals("/api/appraisal/getElevatorAppraisal")
                && !request.getServletPath().equals("/api/resetPassword")
                && !request.getServletPath().equals("/api/planDetail/importExcel")
                && !request.getServletPath().equals("/api/checkItem/importExcel")
                && !request.getServletPath().equals("/api/checkItem/uploadExcel")
                && !request.getServletPath().equals("/api/party/queryPartyByPartyLevel")
                && !request.getServletPath().equals("/api/paperlessMaint/add")
                && !request.getServletPath().equals("/api/emergencyRescue/addWorkOrder")
                && !request.getServletPath().equals("/api/maintenance/traction")
                && !request.getServletPath().equals("/api/maintenance/escalator")
                && !request.getServletPath().equals("/api/maintenance/hydpress")
                && !request.getServletPath().equals("/api/maintenance/debris")
                && !request.getServletPath().equals("/api/repairInfo/addElevator")
                && !request.getServletPath().equals("/api/elevator/add")
                && !request.getServletPath().equals("/api/elevator/updateFlag")
                && !request.getServletPath().equals("/api/elevator/elevatorUnit")
                && !request.getServletPath().equals("/api/party/queryCompanyNameList")
                && !request.getServletPath().equals("/api/user/uploadElevatorLedger")
                && !request.getServletPath().equals("/api/user/uploadElevatorLedgerType")
                && !request.getServletPath().equals("/api/elevator/listMaintenancePartyInterface")
                && !request.getServletPath().equals("/api/elevator/listMaintenanceRecordsInterface")
                && !request.getServletPath().equals("/api/elevator/listMaintenanceProjectInterface")
        ){
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                response.setStatus(200);
                response.setCharacterEncoding("utf-8");
                response.setContentType("text/html; charset=utf-8");
                //解决跨域
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
                response.setHeader("Access-Control-Allow-Credentials","true");
                PrintWriter printWriter =response.getWriter();
                Map map = new HashMap<String,Object>();
                map.put("status",401);
                map.put("message","认证失败");
                printWriter.write(JSON.toJSON(map).toString());
                printWriter.flush();
                printWriter.close();
    //            ((HttpServletResponse) servletResponse)
    //                    .sendError(HttpServletResponse.SC_UNAUTHORIZED, "Missing or invalid Authorization header.");
                return;
            }

            try {
                Claims claims = TokenUtils.parseToken(authHeader);
                request.setAttribute("claims", claims);
            } catch (final Exception e) {
                logger.warn("[doFilter] SignatureException", e);
    //            ((HttpServletResponse) servletResponse)
    //                    .sendError(HttpServletResponse.SC_UNAUTHORIZED, "非法操作");
                response.setStatus(200);
                response.setCharacterEncoding("utf-8");
                response.setContentType("text/html; charset=utf-8");
                //解决跨域
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                response.setHeader("Access-Control-Max-Age", "3600");
                response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization");
                response.setHeader("Access-Control-Allow-Credentials","true");
                PrintWriter printWriter =response.getWriter();
                Map map = new HashMap<String,Object>();
                map.put("status",401);
                map.put("message","认证失败");
                printWriter.write(JSON.toJSON(map).toString());
                printWriter.flush();
                printWriter.close();
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }


    public Map<String, Object> transfor(org.json.JSONObject jsonObject, Map<String, Object> map) {
        try {
            for (Iterator iter = jsonObject.keys(); iter.hasNext();) {
                String key = iter.next().toString();
                // 如果是map
                if (jsonObject.get(key) instanceof org.json.JSONObject) {
                    Map<String, Object> a = new HashMap<String, Object>();
                    // 回调
                    transfor((org.json.JSONObject) jsonObject.get(key), a);
                    map.put(key, a);
                }
                // 如果是list
                else if (jsonObject.get(key) instanceof org.json.JSONArray) {
                    List list = new ArrayList();
                    org.json.JSONArray array = (org.json.JSONArray) jsonObject.get(key);
                    for (int i = 0; i < array.length(); i++) {
                        if (array.get(i) instanceof org.json.JSONObject) {
                            Map<String, Object> a = new HashMap<String, Object>();
                            // 回调
                            transfor((org.json.JSONObject) array.get(i), a);
                            list.add(a);
                        } else {
                            list.add(array.get(i));
                        }
                    }
                    map.put(key, list);
                }
                // 如果都不是
                else {
                    if (jsonObject.isNull(key)) {
                        map.put(key, null);
                    } else {
                        map.put(key, jsonObject.get(key));
                    }
                }
            }
        } catch (Exception e) {
        }
        return map;
    }

}
